#include "common.hpp"
#include "log.hpp"
#include "addr.hpp"
using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << " please use: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    // 1` 创建套接字：
    int sd = socket(AF_INET, SOCK_STREAM, 0); // 网络通信/字节流
    if (sd < 0)
        use_log(loglevel::DEBUG) << "socket failure!";
    use_log(loglevel::DEBUG) << "socket success!";
    // 2`os自己认识用户端机器的ip+随机会生成端口号port自动绑定与解除;故无需bind/程序终止立刻解除故查不到状态
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    // 3`进行连接；进入服务端的listen队列：
    inetaddr ir(ip, port);
    int n = connect(sd, (sockaddr *)ir.addrptr(), ir.addrlen());
    if (n < 0)
    {
        use_log(loglevel::DEBUG) << "connet failure!";
        exit(CONNECT_ERR);
    }
    use_log(loglevel::DEBUG) << "connet success!";
    while (1)
    {
        string line;
        cout << "Please Enter# ";
        getline(std::cin, line);
        //cout<<line.size()<<endl;
        if(line.size()==0) continue;//防止空串被发送；此时服务端一直read（以为客户端还没发送；然后客户端一直read服务端发的信息；这里特殊判断一下）
        write(sd, line.c_str(), line.size());
        char buff[1024];
        int n = read(sd, buff, sizeof(buff));

        if (n > 0)
        {
            buff[n] = 0;
            cout << buff << endl;
        }
    }
    close(sd);
    return 0;
}
